import { ScrollView, View, Text, Image } from '@tarojs/components';
import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui"
import "taro-ui/dist/style/components/modal.scss";
import { connect } from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import moment from 'dayjs';
import Blank from '@/pages/common/blank';
import notdataImg from '@/assets/image/none/none.png'

const flowState = (status) => {
  if (status == 1) {//电路故障
    return '电路故障';
  } else if (status == 2) {//自来水管故障
    return '自来水管故障';
  } else if (status == 3) {//供暖设备故障
    return '供暖设备故障';
  } else if (status == 4) {//家电维修
    return '家电维修';
  } else {//其他
    return '其他';
  }
};

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      isShow: false,
      refresherTriggered: false,
      tabList: [
        { status: 0, text: '待处理' },
        { status: 1, text: '处理中' },
        { status: 2, text: '已处理' },
      ],
    };
  }

  componentDidMount() { }

  componentDidShow() {
    this.props.actions.init()
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  renderTabList(list) {
    let listView = [];
    let {
      main: { curNow },
      actions: { action },
    } = this.props;
    list.map(item => {
      listView.push(
        <View
          className='t_view'
          onClick={() => {
            action.commonChange('main.curNow', item.status)
            action.page()
          }}>
          <Text className={curNow == item.status ? 't_a_text' : 't_text'}>
            {item.text}
          </Text>
          <View
            className={curNow == item.status ? 't_a_border' : 't_border'}></View>
        </View>
      );
    });
    return listView;
  }

  renderList(list) {
    let listView = [];
    list.map(item => {
      listView.push(
        <View className='list'>
          <View
            className='r_sb'
            onClick={(e) => {
              e.stopPropagation();
              Taro.setStorageSync(`repairDetail`, item);
              Taro.navigateTo({
                url: '/pages/package-A/repair/detail/index'
              })
            }}>
            <View style={{ flexDirection: 'row' }}>
              <Text className='typeName' style={{ marginRight: '15px' }}>
                报修类型:
              </Text>
              <Text className='typeName'>
                {flowState(item.type)}
              </Text>
            </View>
            <View>
              <Text className='createTime'>
                {moment(item.createTime).format('YYYY-MM-DD')}
              </Text>
            </View>
          </View>
          <View
            className='descBox'
            onClick={(e) => {
              e.stopPropagation();
              Taro.setStorageSync(`repairDetail`, item);
              Taro.navigateTo({
                url: '/pages/package-A/repair/detail/index'
              })
            }}>
            <Text className='desc'>
              报修描述: &nbsp;
              {item.description}
            </Text>
          </View>
          {item.refImage && item.refImage.length > 0 && (
            <View className='refImageBox'>
              {this.imgRender(item.refImage)}
            </View>
          )}
          <View
            onClick={(e) => {
              e.stopPropagation();
              Taro.setStorageSync(`repairDetail`, item);
              Taro.navigateTo({
                url: '/pages/package-A/repair/detail/index'
              })
            }}>
            <Text className='desc'>
              联系方式: {item.alternatePhone}
            </Text>
          </View>
        </View>
      );
    });
    return listView;
  }

  imgRender(imgList) {
    const imgLists = [];
    const urls = []
    imgList.map((item, index) => {
      urls.push(item.imageUrl)
      imgLists.push(
        <View>
          <Image
            className="img"
            key={item.imageUrl}
            onClick={this.onImageClick.bind(this, item, urls)}
            src={item.imageUrl}
          />
        </View>,
      );
    });
    return imgLists;
  }

  onImageClick = (item, urls) => {
    this.previewImage(item.imageUrl, urls);
  }

  previewImage = (img, files) => {
    Taro.previewImage({
      current: img, // 当前显示图片的http链接
      urls: files, // 需要预览的图片http链接列表
    });
  };


  _onScrollToLower = () => {
    let {
      main: { pageNum, totalPage },
      actions: { action }
    } = this.props;
    let num = pageNum + 1;
    if (num == totalPage) return;
    this.props.actions.action.commonChange('main.pageNum', num)
    this.props.actions.action.page()
  };

  _onRefresherRefresh = () => {
    const { refresherTriggered } = this.state;
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });
    this.props.actions.action.commonChange('main.pageNum', 0);
    this.props.actions.action.page()
    setTimeout(() => {
      this.setState({
        refresherTriggered: false,
      });
    }, 2000);
  };

  async addClick() {
    let itemStr = Taro.getStorageSync('b2b-wechat@login')
    if (!itemStr) {
      Taro.navigateTo({
        url: '/pages/package-C/login/login/index',
      });
      return
    }
    if (itemStr.user.status == 3) {
      Taro.navigateTo({
        url: '/pages/package-A/repair/add/index'
      })
    } else {
      this.setState({ isShow: true })
    }
  }

  render() {
    let { tabList, refresherTriggered, isShow } = this.state;
    let {
      main: { repairList, pageNum, totalPage, isLoading },
      actions: { action },
    } = this.props;
    return (
      <View className="packageARepair" >
        <View className='t_row'>
          {this.renderTabList(tabList)}
        </View>
        <ScrollView
          className='scrollView'
          scrollY
          onScrollToLower={this._onScrollToLower}
          refresherEnabled={true}
          refresherTriggered={refresherTriggered}
          onRefresherPulling={this._onRefresherRefresh}>
          {
            repairList && repairList.length > 0 ?
              this.renderList(repairList) :
              <Blank
                content="您还没有报修信息哦~"
                img={notdataImg}
                imgStyle={{ width: '400rpx', height: '400rpx' }}
                textStyle={{
                  fontSize: '32rpx', color: '#999999', textAlign: 'center', marginTop: '40rpx'
                }}
              />}
          {repairList.length != 0 && pageNum + 1 != totalPage && <View className="status">加载中</View>}
          {
            !isLoading && repairList.length != 0 && pageNum + 1 == totalPage && (
              <View className="status">没有更多了</View>
            )
          }
        </ScrollView>
        <View className="bottom">
          <View className="btn_box">
            <Text className='btn-release'
              onClick={() => {
                this.addClick()
              }}
            >新增报修</Text>
          </View>
        </View>
        {
          isShow &&
          <AtModal
            isOpened={isShow}
            title='温馨提示'
            cancelText='取消'
            confirmText='去绑定'
            onClose={() => {
              this.setState({
                isShow: false,
              });
            }}
            onCancel={() => {
              this.setState({
                isShow: false,
              });
            }}
            onConfirm={() => {
              this.setState({
                isShow: false,
              }, () => {
                Taro.navigateTo({
                  url: '/pages/package-A/house/add/index'
                })
              });
            }}
            content='绑定房屋后才能使用此功能，请先去绑定哦～'
          />
        }
      </View>
    );
  }
}
